﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Models;
using DevExpress.Web.Mvc;
using System.Data;
using Newtonsoft.Json;
using ElingOA6_Admin_DSJCJ.Areas.Admin.Models;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 问卷主题管理
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class PaperController : AdminBaseController
    {
        //
        // GET: /Admin/Paper/
        /// <summary>
        /// 问卷主题管理主页
        /// </summary>
        /// <returns>视图</returns>
        [AuthorityActionFilter("m_Paper", Order = 1)]
        [LogPageActionFilter("问卷主题管理", Order = 2)]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 树
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult PaperTree() 
        {
            TreeModelList treeModelList = new TreeModelList();
            BLL.PaperCls paperClsBll = new BLL.PaperCls();
            List<Model.PaperCls> paperClsAllList = paperClsBll.GetModelList(GlobalConstant.ENTITYNO);

            TreeItemModel treeParentItemModel = new TreeItemModel(null)
            {
                Id = "0",
                Name = "问卷类别列表",
                ImageUrl = Url.Content("~/Content/ControlImages/scripts_code.png")

            };

            List<Model.PaperCls> paperClsList = paperClsAllList.Where(c => c.FPaperClsNo != null).ToList();

            if (paperClsList.Count > 0)
            {
                foreach (Model.PaperCls paperCls in paperClsList)
                {
                    TreeItemModel treeSonItemModel = new TreeItemModel(treeParentItemModel)
                    {
                        Id = paperCls.FPaperClsNo,
                        Name = paperCls.FPaperClsName,
                        ImageUrl = Url.Content("~/Content/ControlImages/scripts_code.png")

                    };

                    treeParentItemModel.Id = "%!^" + treeParentItemModel.Id;

                }
            }
            treeModelList.Add(treeParentItemModel);

            return View(treeModelList);  
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="paperClsNo">类别编号</param>
        /// <returns>返回视图</returns>
        public ActionResult PaperList(string paperClsNo) 
        {
            int pageIndex = 1;

            List<Model.Paper> paperModelList = GetPaperList(paperClsNo, pageIndex);
            ViewData["paperClsNo"] = paperClsNo;

            return View(paperModelList);        
        }

        /// <summary>
        /// 获取数据方法
        /// </summary>
        /// <param name="paperClsNo">类别编号</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageRowSize">页行数</param>
        /// <returns>数据集合</returns>
        private List<Model.Paper> GetPaperList(string paperClsNo, int pageIndex, int pageRowSize = 0) 
        {
            if (null != paperClsNo)
            {
                paperClsNo = Fetch.estimateString(paperClsNo, CheckGetEnum.Safety);
            }
            else 
            {
                paperClsNo = string.Empty;
            }
            BLL.Paper paperBll = new BLL.Paper();
            string where = " FEntityNo='" + GlobalConstant.ENTITYNO + "'";

            if (paperClsNo != "")
            {
                where += "and FPaperClsNo='" + paperClsNo + "'";
            }

            BLL.Common commonBll = new BLL.Common();
            string fiedls = "*";
            int total;

            DataSet ds = commonBll.GetListByPage("v_Paper_Cls", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, where, "FPaperClsNo", 0, out total);

            List<Model.Paper> paperAllList = new List<Model.Paper>();
            List<Model.Paper> paperList = paperBll.DataTableToListPaper(ds.Tables[0]);

            pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                paperAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (paperList.Count > i)
                {
                    paperAllList[((pageIndex - 1) * pageRowSize) + i] = paperList[i];
                }
            }
            return paperAllList;
        }

        /// <summary>
        /// 用于刷新
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult PaperListPartial() 
        {

            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string paperClsNo = Request.Params["paperClsNo"];
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }


            List<Model.Paper> paperList = GetPaperList(paperClsNo, pageIndex, pageRowSize);

            return PartialView("PaperListPartial", paperList);     
        }

        /// <summary>
        /// 初始化页面
        /// </summary>
        /// <param name="fPaperId">类别编号</param>
        /// <returns>视图</returns>
        public ActionResult PaperContent(string fPaperId, string fPaperClsNo) 
        {
            ViewData["FEmpName"] = "";
            Model.Paper paperModel = new Model.Paper();
            paperModel.FPaperClsName = fPaperClsNo;
            ViewData["cbFbQJ"] = "Y";
            ViewData["cbFbZdbm"] = "Y";
            ViewData["cbFbZdr"] = "Y";
            if (string.IsNullOrEmpty(fPaperId))
            {
                paperModel.FPaperType = "D";
                paperModel.FResultIsOpen = "Y";
                paperModel.FIsRecordName = "N";
                ViewData["resultIsOpen"] = paperModel.FResultIsOpen;
                ViewData["hdMethod"] = "ADD";
                ViewData["HRWorkGrpDutyList"] = "";
                ViewData["HRWorkGrpDutyNewList"] = "";
                ViewData["hidPaperID"] = paperModel.FPaperId;
            }
            else 
            {
                
                fPaperId = Fetch.estimateString(fPaperId, CheckGetEnum.Safety);                
                ViewData["hidPaperID"] = fPaperId;
                ViewData["FEmpName"] = "";
                BLL.Paper paperBll = new BLL.Paper();
                paperModel = paperBll.GetModel(decimal.Parse(fPaperId));
                ViewData["resultIsOpen"] = paperModel.FResultIsOpen;
                ViewData["hdMethod"] = "Edit";
                BLL.PaperReadAuth paperReadAuthBll = new BLL.PaperReadAuth();
                List<Model.PaperReadAuth> paperReadAuthList = paperReadAuthBll.GetModelList("FEntityNo='" + GlobalConstant.ENTITYNO + "'");
                paperModel.FPaperClsName = paperModel.FPaperClsNo;

                List<Model.PaperReadAuth> readAuthList = paperReadAuthBll.GetListAuth(decimal.Parse(fPaperId));

                if (readAuthList.Where(c => c.FPronoun == "ALL").Count() > 0)//全局
                {
                    ViewData["cbFbQJ"] = "Y";
                }
                else {
                    ViewData["cbFbQJ"] = "N";
                
                }

                //指定部门
                var query = from c in readAuthList where c.FPronoun == "ASSIGNDEPT" select c; //指定部门
                if (query.Count() > 0)
                {
                    string _jsonstr = "";
                    string json = "";
                    List<CommonValueModel> commonValueList = new List<CommonValueModel>();
                    CommonValueModel commValue;
                    foreach (Model.PaperReadAuth auth in query)
                    {
                       commValue = new CommonValueModel();
                       commValue.Text = auth.Allname;
                       commValue.Value = auth.FSourceNo;
                       
                       commonValueList.Add(commValue);
                    }

                    List<CommonValueModel> commonValueList1 = new List<CommonValueModel>();
                    CommonValueModel commValue1;

                    foreach (Model.PaperReadAuth auth in query)
                    {
                        commValue1 = new CommonValueModel();
                        commValue1.Text = auth.FProp;
                        commValue1.Value = auth.FSourceNo;
                        commonValueList1.Add(commValue1);
                    }
                    _jsonstr += JsonConvert.SerializeObject(commonValueList);
                    json += JsonConvert.SerializeObject(commonValueList1);
                    ViewData["HRWorkGrpDutyList"] = _jsonstr;
                    ViewData["Prop"] += json;
                    ViewData["HRWorkGrpDutyNewList"] = "";
                    ViewData["cbFbZdbm"] = "Y";
                }
                else
                {
                    ViewData["cbFbZdbm"] = "N";
                }


                //指定人
                query = from c in readAuthList where c.FPronoun == "PERSON" select c;
                if (query.Count() > 0)
                {
                    string strName = string.Empty;
                    string strValue = string.Empty;
                    query.ToList().ForEach(c => { strName += c.Allname + ","; strValue += c.FSourceNo + ","; });
                    ViewData["FEmpName"] = strName.TrimEnd(',');
                    string[] array = strValue.TrimEnd(',').Split(',');
                    ViewData["cbFbZdr"] = "Y";
                    string json = "";
                    json += "[";
                    for (int i = 0; i < array.Length; i++) {
                        json += "{";
                        json += "\"Value\":\"" + array[i] + "\"";
                        json += "},";
                    }                   
                    json = json.Substring(0, json.LastIndexOf(","));
                    json += "]";
                    ViewData["hidEmpNo"] = json;

                }
                else {
                    ViewData["hidEmpNo"] = "";
                    ViewData["cbFbZdr"] = "N";
                }


                BLL.PaperIP paperIPBll = new BLL.PaperIP();
                List<Model.PaperIP> paperIPList = paperIPBll.GetListPaperIP(decimal.Parse(fPaperId));

                var fIsVoteIPControlList = from c in paperIPList where c.FProp == "1" select c;
                if (fIsVoteIPControlList.Count() > 0)
                {
                    BLL.IPGroup groupBll = new BLL.IPGroup();
                    List<Model.IPGroup> groupList1 = new List<Model.IPGroup>(); 
                    foreach (Model.PaperIP model in fIsVoteIPControlList)
                    {
                        Model.IPGroup groupModel = groupBll.GetModel(model.FIPGroupID);
                        groupModel.StrFStartIP = GenerateUtil.LongToIP(groupModel.FStartIP);
                        groupModel.StrFEndIP = GenerateUtil.LongToIP(groupModel.FEndIP);
                        groupList1.Add(groupModel);
                    }
                    ViewData["votegroupIPs"] = JsonConvert.SerializeObject(groupList1);
                }


                fIsVoteIPControlList = from c in paperIPList where c.FProp == "2" select c;
                if (fIsVoteIPControlList.Count() > 0)
                {
                    
                    BLL.IPGroup groupBll = new BLL.IPGroup();
                    List<Model.IPGroup> groupList2 = new List<Model.IPGroup>(); 
                    foreach (Model.PaperIP model in fIsVoteIPControlList)
                    {                        
                        Model.IPGroup groupModel = groupBll.GetModel(model.FIPGroupID);
                        groupModel.StrFStartIP = GenerateUtil.LongToIP(groupModel.FStartIP);
                        groupModel.StrFEndIP = GenerateUtil.LongToIP(groupModel.FEndIP);
                        groupList2.Add(groupModel);
                        
                    }
                    ViewData["lookgroupIPs"] = JsonConvert.SerializeObject(groupList2);
                }


            }
            
            ViewData["clsNoList"] = CommonCode.GetPaperList(GlobalConstant.ENTITYNO);

            return View(paperModel);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="paper">model对象</param>
        /// <returns>视图</returns>
        public ActionResult Save(Model.Paper paper) {

            Model.Paper paperModel = GetPaperModel(GlobalConstant.ENTITYNO);
            List<Model.PaperReadAuth> authList = new List<Model.PaperReadAuth>();
            bool fIsRecordName = CheckBoxExtension.GetValue<bool>("FResultIsOpen");
            if (!fIsRecordName)
            {
                authList = GetReadAuth(GlobalConstant.ENTITYNO);
            }


            List<Model.PaperIP> paperIPList = new List<Model.PaperIP>();
            Model.PaperIP paperIPModel;
            bool fIsVoteIPControl = CheckBoxExtension.GetValue<bool>("joinISIP");
            if (fIsVoteIPControl)
            {
                string[] arrayids = Fetch.Post("hdjoinID").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                
                for (int i = 0; i < arrayids.Length; i++)
                {
                    paperIPModel = new Model.PaperIP();
                    paperIPModel.FIPGroupID = Int32.Parse(arrayids[i]);
                    ViewData["joinGroupID"] += arrayids[i];
                    paperIPModel.FProp = "1";
                    paperIPModel.FPaperId = decimal.Parse(Fetch.Post("hidPaperID"));
                    paperIPList.Add(paperIPModel);
                }
                
            }

            bool fIsLookIPControl = CheckBoxExtension.GetValue<bool>("conISIP");
            if (fIsLookIPControl)
            {
                string[] arrayids = Fetch.Post("hdconID").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < arrayids.Length; i++)
                {
                    paperIPModel = new Model.PaperIP();
                    paperIPModel.FIPGroupID = Int32.Parse(arrayids[i]);
                    ViewData["conGroupID"] += arrayids[i];
                    paperIPModel.FProp = "2";
                    paperIPModel.FPaperId = decimal.Parse(Fetch.Post("hidPaperID"));
                    paperIPList.Add(paperIPModel);
                }

            }
            string type = Fetch.Post("hdMethod");
            BLL.Paper paperBll = new BLL.Paper();
            if (type == "ADD")//增加
            {
                try
                {
                    decimal addPaperID = paperBll.AddPaperAndReadAuth(paperModel, authList, paperIPList);
                    Response.Write("<script>alert('增加保存成功');window.location.href='" + Url.Action("PaperList", "Paper", new { paperClsNo = paper.FPaperClsNo }) + "'</script>");
                    Response.Flush();
                    Response.End();
                }
                catch (Exception)
                {
                    Response.Write("<script>alert('增加保存失败')</script>");
                    Response.Flush();
                    Response.End();
                }
            }
            else if (type == "Edit")
            {
                try
                {
                    paperBll.UpdPaperAndReadAuth(paperModel, authList, paperIPList);
                    Response.Write("<script>alert('修改保存成功');window.location.href='" + Url.Action("PaperList", "Paper", new { paperClsNo = paper.FPaperClsNo }) + "'</script>");
                    Response.Flush();
                    Response.End();
                }
                catch (Exception)
                {
                    Response.Write("<script>alert('修改保存失败')</script>");
                    Response.Flush();
                    Response.End();
                }
            }

            ViewData["clsNoList"] = CommonCode.GetPaperList(GlobalConstant.ENTITYNO);
            ViewData["FEmpName"] = "";
            ViewData["joinISIP"] = true;
            ViewData["conISIP"] = true;

            return View("PaperContent", paper);
        }


        /// <summary>
        /// 得到一个Paper对象
        /// </summary>
        /// <param name="entityNo">公司编号</param>
        /// <returns>model对象</returns>
        private Model.Paper GetPaperModel(string entityNo)
        {
            Model.Paper model = new Model.Paper();
            if (Fetch.Post("FBeginDate").Trim() != string.Empty)
            {
                model.FBeginDate = DateTime.Parse(Fetch.Post("FBeginDate"));
            }
            model.FContent = Fetch.Post("FContent").Trim();
            if (Fetch.Post("FEndDate").Trim() != string.Empty)
            {
                model.FEndDate = DateTime.Parse(Fetch.Post("FEndDate"));
            }
            model.FEntityNo = GlobalConstant.ENTITYNO;
            model.FIsRecordName = CheckBoxExtension.GetValue<bool>("FIsRecordName") == true ? "Y" : "N";
            model.FPaperClsNo = DropDownEditExtension.GetValue<string>("FPaperClsNo");
            model.FPaperType = DropDownEditExtension.GetValue<string>("FPaperType");
            model.FPubDate = DateTime.Now;
            model.FPubDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
            model.FPubEmpNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            model.FPubIp = GenerateUtil.GetClientIPv4Address();
            model.FResultIsOpen = CheckBoxExtension.GetValue<bool>("FResultIsOpen") == true ? "Y" : "N";
            model.FTitle = Fetch.Post("FTitle").Trim();

            model.FIsVoteIPControl = CheckBoxExtension.GetValue<bool>("joinISIP") == true ? "Y" : "N";
            model.FIsLookIPControl = CheckBoxExtension.GetValue<bool>("conISIP") == true ? "Y" : "N";
            string hidPaperID = Fetch.Post("hidPaperID");
            if (hidPaperID != "0")
            {
                model.FPaperId = decimal.Parse(Fetch.Post("hidPaperID"));
            }  


            return model;
        }


        /// <summary>
        /// 得到一个ReadAuth对象
        /// </summary>
        /// <param name="entityNo">公司编号</param>
        /// <returns>数据集合</returns>
        private List<Model.PaperReadAuth> GetReadAuth(string entityNo)
        {
            List<Model.PaperReadAuth> authList = new List<Model.PaperReadAuth>();
            Model.PaperReadAuth model;
            bool cbFbQJ = CheckBoxExtension.GetValue<bool>("cbFbQJ");
            if (cbFbQJ)
            {
                model = new Model.PaperReadAuth();
                model.FEntityNo = entityNo;
                model.FPronoun = "ALL";
                authList.Add(model);
            }

            bool cbFbZdbm =CheckBoxExtension.GetValue<bool>("cbFbZdbm");
            if (cbFbZdbm)
            {
                string strBms = Fetch.Post("hdHRWorkGrpDutyList");
                if (strBms != "")
                {
                    List<CommonValueModel> commonValueList = JsonConvert.DeserializeObject<List<CommonValueModel>>(strBms);
                    foreach (CommonValueModel commValue in commonValueList)
                    {
                        model = new Model.PaperReadAuth();
                        model.FEntityNo = entityNo;
                        model.FPronoun = "ASSIGNDEPT";
                        model.FProp = Fetch.Post("cbo_Dept" + commValue.Value);
                        model.FSourceNo = commValue.Value;
                        authList.Add(model);
                    }
                }
            }

            bool cbFbZdr = CheckBoxExtension.GetValue<bool>("cbFbZdr");
            if (cbFbZdr)
            {
                if (Fetch.Post("hidEmpNo").Trim() != "")
                {
                    string json = Fetch.Post("hidEmpNo").Trim();
                    //string[] arrayRy = Fetch.Post("hidEmpNo").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                    List<CommonValueModel> commonValueList = JsonConvert.DeserializeObject<List<CommonValueModel>>(json);
                   // CommonValueModel commonValueModel = new CommonValueModel();
                    //for (int i = 0; i < arrayRy.Length; i++) {
                    //    commonValueModel = new CommonValueModel();
                    //    commonValueModel.Value = arrayRy[i];
                    //    commonValueModel.Text = "";
                    //    commonValueList.Add(commonValueModel);
                    //}
                    foreach (CommonValueModel commonValueModel in commonValueList)
                    {
                        model = new Model.PaperReadAuth();
                        model.FEntityNo = entityNo;
                        model.FPronoun = "PERSON";
                        model.FSourceNo = commonValueModel.Value;
                        authList.Add(model);
                    }
                }
            }


            return authList;
        }



        /// <summary>
        /// 删除主题和主题查看权限
        /// </summary>
        /// <param name="fPaperId">主题编号</param>
        /// <returns>是否删除成功</returns>
        public string DelPaperAndReadAuth(string fPaperId)
        {
            string str = "";
            BLL.PaperTopic topicBll = new BLL.PaperTopic();
            if (topicBll.ExistsPaperID(decimal.Parse(fPaperId)))
            {
                str = "Exists";
            }
            else
            {
                BLL.Paper paperBll = new BLL.Paper();
                try
                {
                    paperBll.DelPapetAndReadAuth(decimal.Parse(fPaperId));
                    str = "ok";
                }
                catch (Exception)
                {
                    str = "error";
                }
            }
            return str;
        }


        /// <summary>
        /// 删除ReadAuth
        /// </summary>
        /// <param name="fPaperId">主题编号</param>
        /// <param name="fSourceNo">操作人</param>
        /// <param name="fPronoun">操作部门</param>
        /// <param name="fProp">类型</param>
        /// <returns>是否删除成功</returns>
        public string DelReadAuth(decimal fPaperId, string fSourceNo, string fPronoun, string fProp)
        {
            string str = "";
            BLL.PaperReadAuth readAuthBll = new BLL.PaperReadAuth();
            try
            {
                readAuthBll.DeleteDept(fPaperId, fSourceNo, fPronoun, fProp,GlobalConstant.ENTITYNO);
                str = "ok";
            }
            catch (Exception)
            {
                str = "error";
            }

            return str;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult ChooseJoinIP(string paperID)
        {
            string entityNo = GlobalConstant.ENTITYNO;     
            BLL.IPGroup groupBll = new BLL.IPGroup();
            List<Model.IPGroup> groupIPList = groupBll.GetModelByEntity(entityNo);
            foreach (Model.IPGroup model in groupIPList)
            {
                model.StrFStartIP = GenerateUtil.LongToIP(model.FStartIP);
                model.StrFEndIP = GenerateUtil.LongToIP(model.FEndIP);
            }


            ViewData["groupIPList"] = JsonConvert.SerializeObject(groupIPList);

            
            return View();
        }


    }
}
